package controller.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.User;

import db.DAOFactory;

import tools.MD5_Encoding;

/**
 * 
 * Description: 对用户登录，登出，删除帐户，注册等请求进行处理。
 * 
 * @since  2009/3/1
 * @author ashen
 * 
 */
public class UserDo extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UserDo() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doDelete method of the servlet. <br>
	 *
	 * This method is called when a HTTP delete request is received.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doDelete(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String msg="";
		
		//获取请求要获取的用户信息的ID，根据ID来返回信息
		String uri=request.getRequestURI();
		String[] uriStr=uri.split("/");
        int userId=Integer.parseInt(uriStr[uriStr.length-1]);
        User activeUser = (User)request.getSession().getAttribute("activeUser");
        if(activeUser.getId().equals(userId)){
	        if(DAOFactory.getUserDAO().delete(userId)){
	        	msg="删除成功";
	        	request.getSession().setAttribute("activeUser",null);
	        }else
	        	msg="删除失败";
        }else
        	msg="删除失败,你没有权限删除该用户。";
		
		out.println("<p>"+msg+"</p>");
		out.flush();
		out.close();
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
        User activeUser = (User)request.getSession().getAttribute("activeUser");
		if(activeUser!=null){
	        out.println("<p class=\"userId\" id=\""+activeUser.getId()+"\">"
	    			+activeUser.getNickName()+",欢迎来访。</p>");
	    	out.println("<p>登录时间：</p>");
	    	out.println("<p>"+new Date()+"</p>");
	    	out.println("<a id=\"logout\">登出</a>");
	    	out.println("<a id=\"deleteUser\">删除用户</a>");
	    	out.flush();
			out.close();
		}
		
		
		
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String msg="";
		
		//获取请求的类型，根据请求的类型分别执行登录，登出，注册三种操作
		String uri=request.getRequestURI();
		String[] uriStr=uri.split("/");
        String requestType=uriStr[uriStr.length-1];
        if(requestType.equals("logout")){
        	//登出操作
        	User activeUser = (User)request.getSession().getAttribute("activeUser");
    		if(activeUser!=null){
    			msg=activeUser.getNickName()+",登出成功！";
    	    	request.getSession().setAttribute("activeUser",null);
    	    	out.println("<p>"+msg+"</p>");
    		}else{
    			msg="你还没有登录！";
    			out.println("<p>"+msg+"</p>");
    		}
        }else{ 
        	String rand = (String)request.getSession().getAttribute("random");
			//验证验证码
	        if(!rand.equals(request.getParameter("random"))){
	        	msg="验证码错误！";
	        	out.println("<p>"+msg+"</p>");
	        	out.println("<a class=\"back\">返回</a>");
	        }else{
	        	if(requestType.equals("login")){
	        		//登录操作
		        	//验证用户名
		        	String userName=request.getParameter("userName");
					User activeUser =DAOFactory.getUserDAO().findByName(userName);
					if(activeUser==null){
						msg="没有该用户名，登录失败！";
						out.println("<p>"+msg+"</p>");
						out.println("<a class=\"back\">返回</a>");
					}else{
						//验证密码
						MD5_Encoding md5=new MD5_Encoding();
				    	String MD5_pwd=md5.getMD5ofStr(request.getParameter("userPassword"));
				        if(!activeUser.getPassword().equals(MD5_pwd)){
				        	msg="密码错误，登录失败！";
				        	out.println("<p>"+msg+"</p>");
				        	out.println("<a class=\"back\">返回</a>");
				        }else{
				        	msg=activeUser.getNickName()+"登录成功！";
				        	request.getSession().setAttribute("activeUser",activeUser);
				        	out.println("<p class=\"userId\" id=\""+activeUser.getId()+"\">"
				        			+activeUser.getNickName()+",欢迎来访。</p>");
				        	out.println("<p>登录时间：</p>");
				        	out.println("<p>"+new Date()+"</p>");
				        	out.println("<a id=\"logout\">登出</a>");
				        	out.println("<a id=\"deleteUser\">删除用户</a>");
				        }		
					}
		        }else if(requestType.equals("register")){
		        	//注册操作
		        	User user =new User();
					user.setName(request.getParameter("userName"));
					//验证用户名是否被使用，用户名不能重复
					User tempUser=DAOFactory.getUserDAO().findByName(user.getName());
					if(tempUser==null){
						user.setNickName(request.getParameter("userNickName"));
						MD5_Encoding md5=new MD5_Encoding();
				    	String MD5_pwd=md5.getMD5ofStr(request.getParameter("userPassword"));
				        user.setPassword(MD5_pwd);
						user.setProfile(request.getParameter("profile"));
						user.setCreateDate(new Date());
						//保存用户到数据库
						if(DAOFactory.getUserDAO().save(user)){
							//注册成功
							msg="注册成功";
							out.println("<p>"+msg+"</p>");
							User activeUser=DAOFactory.getUserDAO().findByName(user.getName());
							request.getSession().setAttribute("activeUser",activeUser);
							out.println("<a class=\"back\">返回</a>");
						}else{
							//注册失败
							msg="注册失败";
							out.println("<p>"+msg+"</p>");
							out.println("<a class=\"back\">返回</a>");
						}
					}else{
						//注册失败,用户名已被使用
						msg="注册失败,用户名已被使用";
						out.println("<p>"+msg+"</p>");
						out.println("<a class=\"back\">返回</a>");
					}
		        }				
			}
        }

		out.flush();
		out.close();
	}

	/**
	 * The doPut method of the servlet. <br>
	 *
	 * This method is called when a HTTP put request is received.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPut(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String msg="";
		//验证验证码
		String rand = (String)request.getSession().getAttribute("random");
        if(!rand.equals(request.getParameter("random")))
        	msg="验证码错误！";
        else{
        	User activeUser = (User)request.getSession().getAttribute("activeUser");
			if(activeUser!=null){
				activeUser.setNickName(request.getParameter("userNickName"));
				//获取密码
				MD5_Encoding md5=new MD5_Encoding();
		    	String MD5_pwd=md5.getMD5ofStr(request.getParameter("userPassword"));
		    	activeUser.setPassword(MD5_pwd);
		    	activeUser.setProfile(request.getParameter("profile"));
				if(DAOFactory.getUserDAO().update(activeUser)){
					msg=activeUser.getNickName()+"，修改用户信息成功！";
					request.getSession().setAttribute("activeUser",activeUser);
				}else
					msg="修改用户信息失败！";
			}else
				msg="用户名已被使用，修改用户信息失败！";
        }
		
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.println(msg);
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
